import { getListApi } from "@/api/financialManagement/payableManagement/agencyBalance";
import CommonHook from "@/hook/commonHook";
import { computed, Ref } from "vue";

export default function OperationHook(state: {
  loading: Ref<boolean>;
  searchForm: AgencyBalance.SearchForm;
  tableColumn: Ref<Array<SuperTable.NestTableColumnItem | SuperTable.TableCoulmnItem>>;
  tableData: Ref<AgencyBalance.ListRows[]>;
  drawerOpts: Base.DrawerOpts;
  asyncTable: Ref<boolean>;
  tableRef: Ref<any>;
}) {
  const { searchForm, tableData, loading, tableColumn, drawerOpts, asyncTable, tableRef } = state;
  const selectRows = computed<Array<StatementPayable.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { exportJsonToExcel } = CommonHook();
  const searchHandle = () => {
    const params: AgencyBalance.SearchForm = {
      ...searchForm
    };
    loading.value = true;
    return getListApi(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          const tableHeader = data.tableHeadList.filter((t: AgencyBalance.TableHeaderColumn) => t.showFlag === 1);
          tableColumn.value = tableHeader.map((t: AgencyBalance.TableHeaderColumn) => {
            return {
              field: t.fieldCode,
              title: t.fieldName,
              minWidth: "120"
            };
          });
          tableColumn.value.unshift({
            type: "checkbox",
            field: "checkbox",
            minWidth: "50"
          });
          tableColumn.value.push({
            field: "action",
            title: "操作",
            minWidth: "100",
            fixed: "right",
            renderSlot: "action"
          });
          tableData.value = data.tableDataList || [];
          asyncTable.value = true;
        }
      })
      .finally(() => (loading.value = false));
  };
  // 详情 Details
  const getInfoHandle = (row: AgencyBalance.ListRows) => {
    drawerOpts.title = "详情";
    drawerOpts.width = "1200px";
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  // 导出
  const exportDataHandle = () => {
    const exportField = tableColumn.value.filter((t: any) => t.title && t.title !== "操作");
    const header = [
      exportField.map((t: any) => {
        return t.title;
      })
    ];

    const data = (selectRows.value.length ? selectRows.value : tableData.value).map((t: any) => {
      const result: any = {};
      for (let i = 0; i < exportField.length; i++) {
        const target = exportField[i];
        result[target.field] = (t as any)[target.field];
      }
      return result;
    });

    loading.value = true;
    exportJsonToExcel(header, data, "代理余额");
    loading.value = false;
  };
  return {
    searchHandle,
    getInfoHandle,
    exportDataHandle
  };
}
